<script setup>
import { ElMessage } from 'element-plus'
import { showApi } from '@/api/area'
import { onMounted, ref } from 'vue'
import { addApi, updateApi } from '@/api/supplier'
const emit = defineEmits(['search'])
const ruleFormRef = ref(null)
const dialogVisible = ref(false)
const value = ref([])
const dialogFormData = ref({
  id: null,
  supplierName: null,
  linkName: null,
  linkPhone: null,
})
const resetForm = () => {
  dialogVisible.value = false
  dialogFormData.value = {
    id: null,
    supplierName: null,
    linkName: null,
    linkPhone: null,
  }
}
const areaList = ref()
const getArea = async () => {
  let res = await showApi()
  areaList.value = res
}
const confirm = async () => {
  let res = null
  if (value.value && value.value.length > 0) {
    dialogFormData.value.areaCode = value.value[value.value.length - 1] // 取最后一个作为选中的地区码
  }
  if (dialogFormData.value.id) {
    res = await updateApi(dialogFormData.value)
  } else {
    res = await addApi(dialogFormData.value)
  }
  if (res.code) {
    ElMessage.success('操作成功!')
    resetForm()
    emit('search')
  } else {
    ElMessage.error('操作失败！')
  }
}
// 级联选择器配置 - 简化版
const cascaderProps = {
  expandTrigger: 'hover',
  value: 'id',      // 指定值字段为 id
  label: 'name',    // 指定标签字段为 name
  children: 'children' // 指定子节点字段为 children
}

const handleChange = (value) => {
  console.log(value)
}
onMounted(() => {
  getArea()
})
defineExpose({
  dialogVisible,
  dialogFormData
})
</script>
<template>
  <el-dialog v-model="dialogVisible" style="width: 400px;">
    <el-form ref="ruleFormRef" :model="dialogFormData" :rules="rules">
      <el-row>
        <el-col span="24">
          <el-form-item label="供应商名字" prop="supplierName">
            <el-input v-model="dialogFormData.supplierName" style="width: 300px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span="24">
          <el-form-item label="联系人名字" prop="linkName">
            <el-input v-model="dialogFormData.linkName" style="width: 300px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span="24">
          <el-form-item label="联系人手机号" prop="linkPhone">
            <el-input v-model="dialogFormData.linkPhone" style="width: 300px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span="24">
          <el-form-item label="地区" >
            <div class="m-4">
              <el-cascader v-model="value" :options="areaList" :props="cascaderProps" @change="handleChange" clearable
                style="width: 300px;" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="confirm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>